package com.bjpowernode.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjpowernode.shop.base.BaseMember;
import com.bjpowernode.shop.domain.Prod;
import com.bjpowernode.shop.domain.UserCollection;
import com.bjpowernode.shop.feign.ProductServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.context.Theme;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/p/collection")
public class UserCollectionController extends BaseMember {
    
    @Autowired
    private ProductServiceFeign productServiceFeign; 
    
    @GetMapping("/count")
    public ResponseEntity<Integer> count(){
        return ResponseEntity.ok(userCollectionService.count(
                new LambdaQueryWrapper<UserCollection>().eq(
                        UserCollection::getUserId,getStringUserId())
        ));
    }


    @GetMapping("/prods")
    public ResponseEntity<Page<Prod>> prods(Page<UserCollection> page) {
        // 根据用户id分页查询出商品收藏的列表数据
        Page<UserCollection> userCollectionPage = userCollectionService.page(page, new LambdaQueryWrapper<UserCollection>().eq(
                UserCollection::getUserId, getStringUserId()
        ));
        List<UserCollection> collectionList = userCollectionPage.getRecords();

        if (CollectionUtils.isEmpty(collectionList)){
            return ResponseEntity.ok(null);
        }

        // 获取收藏列表对应的prodIdList
        List<Long> pidList = collectionList.stream().map(UserCollection::getProdId).collect(Collectors.toList());
        
        // 根据prodIdList查询出商品列表数据
        List<Prod> prodList = productServiceFeign.listByPidList(pidList);

        if (CollectionUtils.isEmpty(prodList)){
            return ResponseEntity.ok(null);
        }
        
        // 封装返回值结果集
        Page resultPage = new Page(page.getCurrent(),page.getSize());
        resultPage.setRecords(prodList);
        return ResponseEntity.ok(resultPage);
    }
}
